package slidev

import (
	"dustbe/util"
	"encoding/json"
	"net/http"
	"os"
	"strconv"

	"github.com/gin-gonic/gin"
)

type SlidevMetaItem struct {
	Name     string   `json:"name"`
	Path     string   `json:"path"`
	Cover    string   `json:"cover"`
	Password string   `json:"password"`
	Tags     []string `json:"tags"`
}

type SlidevMeta struct {
	Content []SlidevMetaItem `json:"content"`
	Index   map[string]int   `json:"index"`
}

type InitResponse struct {
	PptNum  int
	CurPpts []SlidevMetaItem
}

func InitQuery(c *gin.Context) {
	maxPptOnePage, _ := strconv.Atoi(c.Query("maxPptOnePage"))
	file, err := os.Open(SlidevIndexPath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "本地文件打开错误"})
		return
	}

	defer file.Close()
	decoder := json.NewDecoder(file)

	var slidevMeta SlidevMeta
	err = decoder.Decode(&slidevMeta)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": "本地meta json解析失败"})
		return
	}

	pptNum := len(slidevMeta.Content)
	var response InitResponse

	response.PptNum = pptNum

	// 当前ppt数量不足以则全部发送
	if maxPptOnePage > pptNum {
		response.CurPpts = slidevMeta.Content
	} else {
		response.CurPpts = slidevMeta.Content[:maxPptOnePage]
	}

	// 否则只发送前 maxPptOnePage 个
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": response})
}

func QueryRangeBlog(c *gin.Context) {
	// min_seq <= id <= max_seq
	max_seq, _ := strconv.Atoi(c.Query("max_seq"))
	min_seq, _ := strconv.Atoi(c.Query("min_seq"))

	file, err := os.Open(SlidevIndexPath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "本地文件打开错误"})
		return
	}

	defer file.Close()
	decoder := json.NewDecoder(file)

	var slidevMeta SlidevMeta
	err = decoder.Decode(&slidevMeta)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "本地meta json解析失败"})
		return
	}

	pptNum := len(slidevMeta.Content)
	if min_seq > max_seq || max_seq >= pptNum {
		c.JSON(http.StatusOK, gin.H{"code": 4003, "data": "索引访问非法"})
		return
	}

	max_seq = util.Min(max_seq, pptNum-1)
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": slidevMeta.Content[min_seq : max_seq+1]})
}
